import random
import requests
from flask import Blueprint, jsonify
from flask_restful import Api,Resource,reqparse
from models.model import UserModel, db

from utlis.SmsTools import SmsTool
from utlis.RedisTools import RedisTool
from utlis.JwtTools import JwtTool

user_bp = Blueprint('user_bp',__name__,url_prefix='/user')

api = Api(user_bp)

class SmsCodeView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('mobile')
        args = req.parse_args()
        code = random.randint(100000,999999)
        s = SmsTool()
        rs =s.send(args['mobile'],code)
        if not rs:
            return jsonify({
                'code':400,
                'msg':'发送失败'
            })
        else:
            return jsonify({
                'code':200,
                'msg':'发送成功'
            })

class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('mobile')
        req.add_argument('code')
        args = req.parse_args()
        key ='sms_%s'%args['mobile']
        rds = RedisTool().rds
        code = rds.get(key)
        if not code:
            return jsonify({
                'code':400,
                'msg':'验证码过期'
            })
        if args['code'] != code.decode():
            return jsonify({
                'code':400,
                'msg':'验证码不正确'
            })
        user_info = UserModel.query.filter(UserModel.mobile == args['mobile']).first()
        if not user_info:
            u = UserModel(
                 mobile=args['mobile']
            )
            db.session.add(u)
            db.session.commit()
        user_info = UserModel.query.filter(UserModel.mobile == args['mobile']).first()
        payload = {
                'uid':user_info.id,
                'mobile':user_info.mobile
        }
        token = JwtTool().create(payload)
        return jsonify({
            'code':200,
            'msg':'登入成功',
            'token':token
        })

api.add_resource(SmsCodeView,'/sms')
api.add_resource(LoginView,'/login')